<template>
  <a-modal
    :title="title"
    :open="visible"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="800px"
    :mask-closable="false"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="客户" name="customerId">
            <a-select
              v-model:value="form.customerId"
              placeholder="请选择客户"
              :disabled="readOnly"
              show-search
              option-filter-prop="label"
              @change="handleCustomerChange"
            >
              <a-select-option
                v-for="customer in customerList"
                :key="customer.customerId"
                :value="customer.customerId"
                :label="customer.companyName"
              >
                {{ customer.companyName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="优惠金额" name="discountAmount">
            <a-input-number
              v-model:value="form.discountAmount"
              placeholder="请输入优惠金额"
              :min="0"
              :precision="2"
              style="width: 100%"
              :disabled="readOnly"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="有效时长(天)" name="validDays">
            <a-input-number v-model:value="form.validDays" placeholder="请输入有效时长" :min="1" style="width: 100%" :disabled="readOnly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remarks">
            <a-input v-model:value="form.remarks" placeholder="请输入备注" :disabled="readOnly" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 只读模式下显示销售人员信息 -->
      <a-row :gutter="24" v-if="readOnly">
        <a-col :span="8">
          <a-form-item label="销售人员" name="salesPerson">
            <span>{{ form.salesPerson || '暂无' }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="报价人ID" name="salerId">
            <span>{{ form.salerId || '暂无' }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="报价人电话" name="salerPhone">
            <span>{{ form.salerPhone || '暂无' }}</span>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 报价单明细 -->
      <a-divider>报价单明细</a-divider>
      <a-form-item v-if="!readOnly">
        <a-button type="primary" @click="addItem" :disabled="!form.customerId">
          <template #icon><plus-outlined /></template>
          添加产品
        </a-button>
      </a-form-item>

      <a-table
        :data-source="form.items"
        :pagination="false"
        :loading="productLoading"
        :row-key="(record, index) => index"
      >
        <a-table-column title="产品名称" data-index="productName" key="productName">
          <template #default="{ record, index }">
            <a-select
              v-if="!readOnly"
              v-model:value="record.productId"
              placeholder="请选择产品"
              show-search
              option-filter-prop="label"
              @change="(value) => handleProductChange(value, index)"
              :disabled="!form.customerId"
            >
              <a-select-option
                v-for="product in productList"
                :key="product.productId"
                :value="product.productId"
                :label="product.productName"
              >
                {{ product.productName }}
              </a-select-option>
            </a-select>
            <span v-else>{{ record.productName }}</span>
          </template>
        </a-table-column>
        <a-table-column title="单价" data-index="unitPrice" key="unitPrice" :width="120">
          <template #default="{ record }">
            <span v-if="readOnly">¥{{ formatCurrency(record.unitPrice) }}</span>
            <a-input-number
              v-else
              v-model:value="record.unitPrice"
              :min="0"
              :precision="2"
              style="width: 100%"
              @change="(value) => calculateTotalPrice(record, record.quantity, value)"
            />
          </template>
        </a-table-column>
        <a-table-column title="数量" data-index="quantity" key="quantity" :width="100">
          <template #default="{ record, index }">
            <span v-if="readOnly">{{ record.quantity }}</span>
            <a-input-number
              v-else
              v-model:value="record.quantity"
              :min="1"
              style="width: 100%"
              @change="(value) => calculateTotalPrice(record, value, record.unitPrice)"
            />
          </template>
        </a-table-column>
        <a-table-column title="小计" data-index="totalPrice" key="totalPrice" :width="120">
          <template #default="{ record }">
            ¥{{ formatCurrency(record.totalPrice) }}
          </template>
        </a-table-column>
        <a-table-column title="备注" data-index="remarks" key="remarks">
          <template #default="{ record }">
            <span v-if="readOnly">{{ record.remarks }}</span>
            <a-input
              v-else
              v-model:value="record.remarks"
              placeholder="请输入备注"
            />
          </template>
        </a-table-column>
        <a-table-column title="操作" key="action" :width="80" v-if="!readOnly">
          <template #default="{ index }">
            <a-popconfirm
              title="确定要删除这个明细吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeItem(index)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </a-table>

      <!-- 金额汇总 -->
      <a-row :gutter="24" style="margin-top: 20px;">
        <a-col :span="12" :offset="12">
          <a-descriptions :column="1" size="small" bordered>
            <a-descriptions-item label="总价">
              <span class="amount-text">¥{{ formatCurrency(totalAmount) }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="优惠金额">
              <span class="amount-text">¥{{ formatCurrency(form.discountAmount) }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="最终金额">
              <span class="amount-text final-amount">¥{{ formatCurrency(finalAmount) }}</span>
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { QuoteCreateRequest, QuoteItemRequest } from '@/types/quote'
import type { Customer } from '@/types/customer'
import type { Product } from '@/types/product'
import * as customerApi from '@/api/customer'
import * as productApi from '@/api/product'
import * as quoteApi from '@/api/quote'
import { formatCurrency } from '@/utils/format'

interface Props {
  visible: boolean
  formData?: Partial<any> // 使用any类型以兼容Quote和QuoteCreateRequest和readOnly属性
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: () => ({})
})

const emit = defineEmits<Emits>()

// 表单相关
const formRef = ref<FormInstance>()
const loading = ref(false)
const productLoading = ref(false)

// 数据列表
const customerList = ref<Customer[]>([])
const productList = ref<Product[]>([])

// 表单数据
const form = reactive<QuoteCreateRequest>({
  quoteId: undefined,
  customerId: undefined,
  discountAmount: 0,
  status: undefined,
  remarks: '',
  // 以下字段由后端自动填充，前端不需要设置
  salesPerson: undefined,
  salerId: undefined,
  salerPhone: undefined,
  validDays: 30,  // 默认30天有效期
  items: []
})

// 是否只读模式
const readOnly = computed(() => {
  return props.formData.readOnly === true
})

// 表单标题
const title = computed(() => {
  if (props.formData.readOnly) return '查看报价单'
  return props.formData.quoteId ? '编辑报价单' : '新增报价单'
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  validDays: [
    { required: true, message: '请输入有效时长', trigger: 'blur' },
    { type: 'number', min: 1, message: '有效时长必须大于0', trigger: 'blur' }
  ]
}

// 计算总价 - 确保追踪到所有 items 及其 totalPrice 的变化
const totalAmount = computed(() => {
  if (!form.items || form.items.length === 0) return 0
  // 通过访问每个 item 的所有相关属性来确保响应式追踪
  return form.items.reduce((sum, item) => {
    const price = item.totalPrice || 0
    // 访问 item 的其他属性以确保响应式追踪
    void item.quantity
    void item.unitPrice
    return sum + price
  }, 0)
})

// 计算最终金额
const finalAmount = computed(() => {
  const total = totalAmount.value
  const discount = form.discountAmount || 0
  return Math.max(0, total - discount)
})

// 初始化加载数据
onMounted(() => {
  loadCustomers()
})

// 加载客户列表
const loadCustomers = async () => {
  try {
    const res = await customerApi.getCustomerList()
    customerList.value = res || []
  } catch (error) {
    message.error('加载客户列表失败')
    console.error('加载客户列表失败:', error)
  }
}

// 加载产品列表
const loadProducts = async () => {
  productLoading.value = true
  try {
    const res = await productApi.getProductList()
    productList.value = res || []
  } catch (error) {
    message.error('加载产品列表失败')
    console.error('加载产品列表失败:', error)
  } finally {
    productLoading.value = false
  }
}

// 客户变化时加载产品列表
const handleCustomerChange = (customerId: number) => {
  if (customerId) {
    loadProducts()
  } else {
    productList.value = []
    form.items = []
  }
}

// 产品变化时更新明细信息
const handleProductChange = (productId: number, index: number) => {
  const product = productList.value.find(p => p.productId === productId)
  if (product && form.items && form.items[index]) {
    const item = form.items[index]
    // 更新产品信息
    item.productName = product.productName
    item.unitPrice = product.unitPrice
    item.quantity = item.quantity || 1

    // 重新计算小计
    calculateTotalPrice(item, item.quantity, item.unitPrice)

    // 确保响应式更新 - 通过重新赋值数组触发更新
    nextTick(() => {
      if (form.items) {
        const items = [...form.items]
        form.items = items
      }
    })
  }
}

// 计算小计
const calculateTotalPrice = (item: QuoteItemRequest, quantity: number | undefined, unitPrice: number | undefined) => {
  const qty = quantity || 0
  const price = unitPrice || 0
  const total = Number((qty * price).toFixed(2))

  // 确保响应式更新 - 直接修改对象属性，Vue 3 的 reactive 会自动追踪
  item.quantity = qty
  item.unitPrice = price
  item.totalPrice = total
}

// 添加明细项
const addItem = () => {
  if (!form.items) {
    form.items = []
  }
  // 添加更完整的初始化数据
  form.items.push({
    productId: undefined,
    productName: '',
    unitPrice: 0,
    quantity: 1,
    totalPrice: 0,
    remarks: ''
  })
}

// 删除明细项
const removeItem = (index: number) => {
  if (form.items) {
    form.items.splice(index, 1)
  }
}

// 监听formData变化，填充表单
watch(() => props.formData, (newVal) => {
  if (newVal) {
    // 清空现有数据
    Object.keys(form).forEach(key => {
      // @ts-ignore
      if (key !== 'items') {
        // @ts-ignore
        form[key] = newVal[key] !== undefined ? newVal[key] : (key === 'discountAmount' ? 0 : '')
      }
    })

    // 特殊处理items
    if (newVal.items && Array.isArray(newVal.items)) {
      form.items = newVal.items.map(item => ({
        itemId: item.itemId,
        productId: item.productId,
        productName: item.productName,
        unitPrice: item.unitPrice || 0,
        quantity: item.quantity || 1,
        totalPrice: item.totalPrice || 0,
        remarks: item.remarks || ''
      }))
    } else {
      form.items = []
    }

    // 如果有customerId，加载产品列表
    if (newVal.customerId) {
      loadProducts()
    }
  }
}, { immediate: true, deep: true })

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formRef.value?.resetFields()
  }
})

// 提交表单
const handleSubmit = async () => {
  if (readOnly.value) {
    handleCancel()
    return
  }

  try {
    await formRef.value?.validate()

    // 验证明细项
    if (!form.items || form.items.length === 0) {
      message.warning('请至少添加一个产品明细')
      return
    }

    // 验证每个明细项
    for (const item of form.items) {
      if (!item.productId) {
        message.warning('请选择产品')
        return
      }
      if (!item.quantity || item.quantity <= 0) {
        message.warning('请输入正确的数量')
        return
      }
    }

    loading.value = true

    // 设置最终金额
    form.discountAmount = form.discountAmount || 0

    const api = form.quoteId ? 'updateQuote' : 'addQuote'
    const method = form.quoteId ? 'update' : 'add'

    if (method === 'add') {
      await quoteApi.addQuote(form)
    } else {
      await quoteApi.updateQuote({ ...form, quoteId: form.quoteId })
    }

    message.success(`${title.value}成功`)
    emit('success')
  } catch (error) {
    message.error(`${title.value}失败`)
    console.error(`${title.value}失败:`, error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.amount-text {
  font-weight: bold;
}

.final-amount {
  color: #ff4d4f;
  font-size: 16px;
}
</style>